package com.etc;


import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;


import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author 上等的猪头肉
 * @Title: WordCount
 * @ProjectName wordcount
 * @Description: TODO
 * @date 2018/11/20 9:37
 */
public class WordCount {

    public static class MapWordCount extends Mapper<LongWritable, Text,Text, IntWritable>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String s = value.toString();
            String[] line = s.split(",");
            for (String s1 : line) {
                context.write(new Text(s1),new IntWritable(1));
            }
        }
    }


    public static class ReduceWordCount extends Reducer<Text,IntWritable,Text,IntWritable>{

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int num = 0;
            for (IntWritable value : values) {
                num  += value.get();

            }  context.write(key,new IntWritable(num));
        }
    }




        public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException, URISyntaxException {

            Configuration conf = new Configuration();

            Job job = Job.getInstance(conf);

            job.setJarByClass(WordCount.class);
            job.setMapperClass(MapWordCount.class);
            job.setReducerClass(ReduceWordCount.class);

            job.setMapOutputKeyClass(Text.class);
            job.setMapOutputValueClass(IntWritable.class);

            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(IntWritable.class);


            FileInputFormat.addInputPath(job,new Path("hdfs://192.168.88.100:9000/input"));
                FileOutputFormat.setOutputPath(job,new Path("hdfs://192.168.88.100:9000/ouput"));

            job.setNumReduceTasks(1);
            System.exit(job.waitForCompletion(true)?0:1);
        }

}
